package com.hmall.item.controller;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.ItemMqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     *
     * @return
     */
    @GetMapping("list")
    public PageDTO<Item> list(@RequestParam Integer page, @RequestParam Integer size) {
        return itemService.selectItemByPage(page, size);
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Item selectItemById(@PathVariable("id") Long id) {
        return itemService.selectItemById(id);
    }

    /**
     * 添加商品
     * @param item
     */
    @PostMapping()
    public void addItem(@RequestBody Item item) {
        itemService.addItem(item);
        // 发送MQ消息
        //rabbitTemplate.convertAndSend(ItemMqConstants.EXCHANGE_NAME, ItemMqConstants.INSERT_KEY, item.getId());
    }

    /**
     * 根据商品id删除商品
     * @param id
     */
    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        itemService.deleteItemById(id);
        // 发送MQ消息
//        rabbitTemplate.convertAndSend(ItemMqConstants.EXCHANGE_NAME, ItemMqConstants.DELETE_KEY, id);
    }

    /**
     * 查看商品上下架
     * @param id
     * @param status
     */
    @PutMapping("status/{id}/{status}")
    public void findItemStatue(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        if (status==1) {
            rabbitTemplate.convertAndSend(ItemMqConstants.EXCHANGE_NAME, ItemMqConstants.INSERT_KEY, id);
        }else{
            rabbitTemplate.convertAndSend(ItemMqConstants.EXCHANGE_NAME, ItemMqConstants.DELETE_KEY, id);
        }
        itemService.findItemStatue(id,status);
    }

    /** 修改商品信息
     * @param item
     */
    @PutMapping()
    public void updateItem(@RequestBody Item item) {
        itemService.updateItem(item);
        // 发送MQ消息
        rabbitTemplate.convertAndSend(ItemMqConstants.EXCHANGE_NAME, ItemMqConstants.INSERT_KEY, item.getId());
    }

    /**
     * 更新库存
     * @param itemId
     * @param num
     */
    @PutMapping("stock/{itemId}/{num}")
    public void updateStock(@RequestParam Long itemId ,@RequestParam Integer num){
        itemService.updateStock(itemId,num);
    }

    /**
     * 恢复库存
     * @param itemId
     * @param num
     */
    @PutMapping("add/{itemId}/{num}")
    public void reliveStock(@RequestParam Long itemId ,@RequestParam Integer num){
        itemService.reliveStock(itemId,num);
    }
}
